package com.fosdata.dpm.util;

import com.fosdata.dpm.entity.dto.PageQueryRequestDTO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.CollectionUtils;

import java.util.*;
import java.util.function.Supplier;

/**
 * Description:
 * Created by yhsh on 2022/7/12 9:41
 * version 2.0
 * 方法说明 基础controller，
 */
public class PageQueryUtil {


    public static Map<String, Object> initPageQuery() {
        Map<String, Object> rspData = new HashMap<>();
        rspData.put("rows", Collections.emptyList());
        rspData.put("pages", 0);
        rspData.put("total", 0);
        return rspData;
    }

    private static Map<String, Object> getDataTable(PageInfo<?> pageInfo) {
        Map<String, Object> rspData = new HashMap<>();
        rspData.put("rows", pageInfo.getList());
        rspData.put("pages", pageInfo.getPages());
        rspData.put("total", pageInfo.getTotal());
        return rspData;
    }

    public static Map<String, Object> selectByPageNumSize(PageQueryRequestDTO request, Supplier<?> s) {
        if(Objects.isNull(request)){
            PageHelper.startPage(1,Integer.MAX_VALUE);
        }else {
            PageHelper.startPage(request.getPageNum(), request.getPageSize());
        }
        PageInfo<?> pageInfo = new PageInfo<>((List<?>) s.get());
        PageHelper.clearPage();
        return getDataTable(pageInfo);
    }

    public static Map<String, Object> selectByPageNumSizeOrderBy(PageQueryRequestDTO request, Supplier<?> s) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), request.getSort() + " " + request.getSortOrder());
        PageInfo<?> pageInfo = new PageInfo<>((List<?>) s.get());
        PageHelper.clearPage();
        return getDataTable(pageInfo);
    }

    public static Map<String, Object> getPageInfo(PageQueryRequestDTO request, List<?> list) {
        Map<String, Object> rspData = new LinkedHashMap<>();
        int count = list.size();
        int pages = (int) Math.ceil(count * 1.0 / request.getPageSize());
        int fromIndex = (request.getPageNum() - 1) * request.getPageSize();
        int toIndex = request.getPageNum() * request.getPageSize();
        if (fromIndex > count) {
            rspData.put("rows", CollectionUtils.isEmpty(list));
            rspData.put("pages", pages);
            rspData.put("total", count);
            return rspData;
        }
        if (toIndex > count) {
            toIndex = count;
        }
        rspData.put("rows", CollectionUtils.isEmpty(list) ? list : list.subList(fromIndex, toIndex));
        rspData.put("pages", pages);
        rspData.put("total", count);
        return rspData;

    }
}
